import jwt
from django.views import View
from django.conf import settings
from django.http import JsonResponse
from users.models import UserProfile


class BaseView(View):
    def dispatch(self, request, *args, **kwargs):
        token = request.META.get("HTTP_AUTHORIZATION")[2:-1]
        key = settings.JWT_TOKEN_KEY

        try:
            payload = jwt.decode(token, key, algorithms="HS256")
            # 若有问题则返回错误被下边捕捉
        except Exception as e:
            print(e)
            return JsonResponse({"code": 403})

        # 给所有用过装饰器的request增加一个对象
        username = payload.get("username")
        # 将username存入request
        user = UserProfile.objects.get(username=username)
        request.myuser = user

        return super().dispatch(request, *args, **kwargs)
